/*
 * $Log: ComplaintFormController.java,v $
 * Revision 1.22  2008/12/18 22:54:23  bgearring
 * added CVS log
 *
 */

package com.redside.webapp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.redside.Constants;
import com.redside.model.Complaint;
import com.redside.model.InitialComplaint;
import com.redside.model.list.OptionsBean;
import com.redside.model.lookup.BusinessCatLkp;
import com.redside.model.lookup.ComplaintStatusLkp;
import com.redside.model.lookup.CountyLkp;
import com.redside.model.lookup.StateLkp;
import com.redside.model.lookup.ViolationTypeLkp;
import com.redside.service.GenericManager;
import com.redside.service.OptionsBeanLookupManager;
import com.redside.util.DateUtil;
import com.redside.webapp.util.CustomBusinessCategoryEditor;
import com.redside.webapp.util.CustomComplaintStatusLookupEditor;
import com.redside.webapp.util.CustomCountyEditor;
import com.redside.webapp.util.CustomStateEditor;
import com.redside.webapp.util.ViolationTypeLookupEditor;


public class ComplaintFormController extends BaseFormController {

    private GenericManager<Complaint, Long> complaintManager = null;
    private OptionsBeanLookupManager optionsBeanManager;

    public void setComplaintManager(GenericManager<Complaint, Long> complaintManager) {
        this.complaintManager = complaintManager;
    }

    public void setOptionsBeanManager(OptionsBeanLookupManager optionsBeanManager) {
        this.optionsBeanManager = optionsBeanManager;
    }

    private static final java.lang.String PARAM_CANCEL = "_cancel";
    
    public ComplaintFormController() {
        setCommandName("complaint");
        setCommandClass(Complaint.class);
        setFormView("complaintForm");
        setSuccessView("redirect:/complaintSuccess.html");
    }
    
    public ModelAndView processFormSubmission(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors) throws Exception {
        if (WebUtils.hasSubmitParameter(request, PARAM_CANCEL)) {
            return new ModelAndView("redirect:/complaintFormCancel.wems");
        }
        
        return super.processFormSubmission(request, response, command, errors);
    }    
    /**
     * Override formBackingObject to set the Complaints on the Complaint
     * form.
     */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        Complaint form = (Complaint) super.formBackingObject(request);
        request.getSession().removeAttribute("message");
        form.setInitialComplaint(new InitialComplaint());
        form.getInitialComplaint().getAddress().setStateId("OR");
        form.getInitialComplaint().getAddress().setCountyId("051");
        form.getInitialComplaint().setComplainantStateId("OR");
        return form;
    }

    public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
            Object command, BindException errors) throws Exception {
    	
    	Complaint complaint = (Complaint) command;
    	boolean isNew = (complaint.getId() == null);
    	String success = getSuccessView();
        Locale locale = request.getLocale();
        
        if (request.getParameter("delete") != null) {
        	complaintManager.remove(complaint.getId());
            saveMessage(request, getText("complaint.deleted", locale));
        } else {
        	logger.debug("=====>PROCESSING: onSubmit for: "+complaint.getInitialComplaint().getBusinessName());
            complaint.getInitialComplaint().getAddress().setStateId("OR");
            complaint.setComplaintStatusId(Long.valueOf(1));
            complaint.setViolationTypeId(Long.valueOf(1));
            complaint.setActionable(false);
            complaint.setFirstValidComplaint(false);
            complaint.setComplaintDate(DateUtil.getCurrentDateTime());
        	complaintManager.save(complaint);
            String key = (isNew) ? "complaint.added" : "complaint.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "redirect:complaintform.html?id=" + complaint.getId();
            }
        }
        
        return new ModelAndView(success);
    }

    protected Map<String, List<OptionsBean>> referenceData(HttpServletRequest request)
            throws Exception {
        Map<String, List<OptionsBean>> complaintLists = new HashMap<String, List<OptionsBean>>();
        complaintLists.put("businessTypes", optionsBeanManager.findAll(
                Constants.BUS_CAT_LIST, "0","Select Business Type"));
        complaintLists.put("countyList", optionsBeanManager.findAll(Constants.COUNTY_LIST,
                "","Select County"));
        complaintLists.put("stateList", optionsBeanManager.findAll(Constants.STATE_LIST));
        return complaintLists;
    }

    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        // convert java.util.Date
        SimpleDateFormat dateFormat = new SimpleDateFormat(ResourceBundle.getBundle(Constants.BUNDLE_KEY,
        		LocaleContextHolder.getLocale()).getString("date.format"));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));

        // convert java.lang.Long
        binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class,
                null, true));
        
        binder.registerCustomEditor(StateLkp.class, new CustomStateEditor(optionsBeanManager));
        binder.registerCustomEditor(CountyLkp.class, new CustomCountyEditor(optionsBeanManager));
        binder.registerCustomEditor(ComplaintStatusLkp.class, new CustomComplaintStatusLookupEditor(optionsBeanManager));
        binder.registerCustomEditor(BusinessCatLkp.class, new CustomBusinessCategoryEditor(optionsBeanManager));
        binder.registerCustomEditor(ViolationTypeLkp.class, new ViolationTypeLookupEditor(optionsBeanManager));
    }
    
    /*    protected ModelAndView processFormSubmission(HttpServletRequest request,
    HttpServletResponse response, Object command, BindException errors)
    throws Exception {
logger.debug("========================>PROCESSING: processFormSubmission");
if (WebUtils.hasSubmitParameter(request, PARAM_CANCEL)) {
    return new ModelAndView("/");
}
return onSubmit(request, response,
        command, errors);
}*/
    
    protected boolean suppressBinding(HttpServletRequest request) {
        if (WebUtils.hasSubmitParameter(request, PARAM_CANCEL)){
            return true;
        } else {
            return false;
        }
    }

    /**
     * Convenience method for getting a i18n key's value.
     * 
     * @param msgKey the i18n key to lookup
     * @return the message for the key
     */
    public String getText(String msgKey) {
        return getMessageSourceAccessor().getMessage(msgKey);
    }

    /**
     * Convenient method for getting a i18n key's value with a single string
     * argument.
     * 
     * @param msgKey the i18n key to lookup
     * @param arg arguments to substitute into key's value
     * @return the message for the key
     */
    public String getText(String msgKey, String arg) {
        return getText(msgKey, new Object[] { arg });
    }

    /**
     * Convenience method for getting a i18n key's value with arguments.
     * 
     * @param msgKey the i18n key to lookup
     * @param args arguments to substitute into key's value
     * @return the message for the key
     */
    public String getText(String msgKey, Object[] args) {
        return getMessageSourceAccessor().getMessage(msgKey, args);
    }

}
